package liuyang.bigeventserver.modules.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import liuyang.bigeventserver.common.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 视频参考：
 * https://www.bilibili.com/video/BV1Fd4y1k7rq/?p=36&spm_id_from=pageDriver&vd_source=8bd7b24b38e3e12c558d839b352b32f4
 * 视频：3:20开始。
 *
 * 注销流程：
 * 前端删掉自己持有的jwt token
 * 后端把redis中存储的jwt token删掉
 *
 * @author liuyang
 * @since 2022/1/25
 *        2024/2/27 更换为jakarta包，并组件化@Component
 */
@Component
@Slf4j
@AllArgsConstructor
public class SessionRespJsonLogoutSuccessHandler implements LogoutSuccessHandler {

    private final ObjectMapper om;
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //ObjectMapper om = new ObjectMapper();

        // For Session
        if (authentication != null && authentication.getDetails() != null) {
            request.getSession().invalidate();
        }

        // For JWT
        // 删掉redis中的jwt token


        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.getWriter().println(om.writeValueAsString(R.ok("注销成功")));

        log.debug("注销成功");
    }
}
